# coding: utf-8

import urllib
import urllib2
import os
import leancloud
import time
import datetime
import json
from leancloud import Object, Query

APPID = 'wx147a7583c9622a1b'
SECRET = 'af4aa163fdd97fb204b1283ece9ed84f'

LEANID = 'm3vGPBDTLcIBYncljScwWGaQ'
LEANKEY = 'o6PmgVg0yHr2cwHMUBctNzvb'

TOKENEXR = 1200

JS_TICKET_ID = '56484aa800b07a1889ee3d74'  # in Cache
ACTOKEN_ID = '563bf85c00b0023ca8c23999' # in Cache
WECHATKFS_ID = '5649285c60b2d1404c49ddeb' # in Cache_dict
WECHATNEWITEMS_ID = '56498c90ddb2084a7bdb48c3' # in Cache_list

Cache = Object.extend('Cache')
WechatUser = Object.extend('WechatUser')

def getactokenfromapi():
    actokenurl = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s'
    result = json.load(urllib2.urlopen(actokenurl % (APPID, SECRET)))
    return result['access_token']

def getaccesstoken(force=False):
    query = Query(Cache)
    query.equal_to('name', 'we_accesstoken')
    try:
        result = query.first()
        if not result:
            raise leancloud.errors.LeanCloudError
    except leancloud.errors.LeanCloudError:
        actoken  = getactokenfromapi()
        Cache(name='we_accesstoken', content=actoken, updatetime=time.time()).save()
        return actoken
    now = time.time()
    # print result.get('updatetime')
    # print now
    # print result.get('updatetime') - now
    if force or result.get('updatetime') + TOKENEXR < now:
        actoken = getactokenfromapi()
        result.set('content', actoken)
        result.set('updatetime', now)
        result.save()
        return actoken
    else:
        return result.get('content')


def get_openids_api():
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()    
    apiurl = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s'
    openids = []
    # actoken = getaccesstoken()
    result = json.load(urllib2.urlopen(apiurl % (ACTOKEN, '')))
    openids.extend(result['data']['openid'])
    while result['total'] > result['count']:
        next_openid = result['data']['next_openid']
        result = json.load(urllib2.urlopen(apiurl % (ACTOKEN, '')))
        openids.extend(result['data']['openid'])
    return openids
    
def get_userinfo_api(openid):
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()     
    apiurl = 'https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN'
    # actoken = getaccesstoken()
    result = json.load(urllib2.urlopen(apiurl % (ACTOKEN, openid)))
    return result
    
def get_save_userinfo_api(openid, refresh=True):    
    query = Query(WechatUser)
    query.equal_to('openid', openid)
    resubcribe = False
    try:
        user = query.first()
        resubcribe = True        
        if not refresh:
            # print 'No refresh, direct return user:'
            user.set('subscribe', 1)
            setNickname_emoji(user)
            user.save()
            return user
    except leancloud.errors.LeanCloudError:
        user = WechatUser(openid=openid)
    result = get_userinfo_api(openid)
    if not result.get('errcode') and result.get('subscribe')!=0:
        items = [
            'subscribe', 'nickname', 'sex', 'language', 'city', 'province', 'country',
            'headimgurl', 'subscribe_time', 'remark', 'groupid']
        #-----Backup user info ---#
        if resubcribe:
            backup = False
            for item in items:
                if user.get(item) != result.get(item):
                    backup = True
            if backup:
                bakuser = Object.extend('WechatUserBackupInfo')()
                for item in items:
                    bakuser.set(item, user.get(item))
                bakuser.save()                    
        #------End backup -----#
        for item in items:
            user.set(item, result[item])
        setNickname_emoji(user)
        user.save()
    return user
    
def setNickname_emoji(user):
    nickname = user.get('nickname')
    if nickname:
        emoji = json.load(open('tools/emoji.json'))
        replaces = set()
        for t in nickname:
            if t in emoji:
                replaces.add(t)
        if replaces:
            for t in replaces:
                nickname = nickname.replace(t, emoji[t])
            user.set('nickname_emoji', nickname)
        else:
            user.unset('nickname_emoji')

    
def sendmessage(openid, content, c_type='text', fromkf=False):
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()     
    url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s'
    data = {'touser': openid}
    if c_type == 'text':
        data['msgtype'] = 'text'
        data['text'] = {'content': content}
    elif c_type == 'news':
        data['msgtype'] = 'news'
        data['news'] = {'articles': content}
    elif c_type == 'image':
        data['msgtype'] = 'image'
        data['image'] = {'media_id': content}
    elif c_type == 'voice':
        data['msgtype'] = 'voice'
        data['voice'] = {'media_id': content}
    elif c_type == 'video':
        data['msgtype'] = 'video'
        data['video'] = {'thumb_media_id': content[0], 'media_id': content[1]}        
    if fromkf:
        # data['customservice'] = {'kf_account': 'test@ysfblgsc'}
        data['customservice'] = {'kf_account': fromkf}
    data = json.dumps(data, 
        ensure_ascii=False
        ).encode('utf-8')
    req = urllib2.Request(url % ACTOKEN, headers={'content-type': 'application/json'})
    ret = json.load(urllib2.urlopen(req, data))
    return ret
    # print ret.read()

def sendmessage2(openid, content, c_type='text'):   #Use Debug API to send emoji
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()     
    url0 = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s'
    url0 = urllib.quote(url0 % ACTOKEN)
    url = 'http://mp.weixin.qq.com/debug/cgi-bin/apiagent?url=%s&method=POST&body=0' % url0
    data = {'touser': openid}
    if c_type == 'text':
        data['msgtype'] = 'text'
        data['text'] = {'content': content}
    elif c_type == 'news':
        data['msgtype'] = 'news'
        data['news'] = {'articles': content}
    data = json.dumps(data, ensure_ascii=False).encode('utf-8')
    data = 'body=%s' % urllib.quote(data)
    ret = urllib2.urlopen(url, data)
    return ret
    
#------------Qr code --------------#
def getqrcode(scene, expire_seconds=60):
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()     
    url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=%s'
    data = {}
    if expire_seconds:
        data['action_name'] = 'QR_SCENE'
        data['expire_seconds'] = expire_seconds
        try:
            scene = int(scene)
        except:
            return 'scene shoud be 32 digits when expire is not None'
    else:
        data['action_name'] = 'QR_LIMIT_STR_SCENE'
    if isinstance(scene, int):
        data['action_info'] = {'scene': {'scene_id': scene}}
    elif isinstance(scene, (str, unicode)) and len(scene) <= 64:
        data['action_info'] = {'scene': {'scene_str': scene}}
    else:
        return 'Scene Faild or Limit'
    ret = json.load(urllib2.urlopen(url % ACTOKEN, json.dumps(data)))
    ticket = ret.get('ticket')
    if ticket:
        qrurl = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=%s' % ticket
        ret['qrurl'] = qrurl
    return ret
    
def sendqrcode(openid, scene, expire_seconds=60):
    ret = getqrcode(scene, expire_seconds)
    qrurl = ret.get('qrurl')
    if qrurl:
        sendimagefromurl(openid, qrurl)
    return ret
    
#-----------------End Qr code---------#
    
#--------------Kf ---------------------#    
def getkflist(online=False):
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()     
    if online:
        url = 'https://api.weixin.qq.com/cgi-bin/customservice/getonlinekflist?access_token=%s'
        retname = 'kf_online_list'
    else:
        url = 'https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=%s'
        retname = 'kf_list'
    ret = json.load(urllib2.urlopen(url % ACTOKEN))

    return ret.get(retname, ret)
    
def refreshkfs():
    kfs = getkflist()
    kfsdict = {}
    cache = Query(Object.extend('Cache_dict')).get(WECHATKFS_ID)
    kfsdict0 = cache.get('content')
    for kf in kfs:
        kf_account = kf.pop('kf_account')
        if (kf_account in kfsdict0 and
            kf.get('kf_headimgurl') == kfsdict0[kf_account].get('kf_headimgurl') and 
            kfsdict0[kf_account].get('kf_headimgurl_cache')):
            kf['kf_headimgurl_cache'] = kfsdict0[kf_account]['kf_headimgurl_cache']
        else:
            url = kf.get('kf_headimgurl')
            if url:
                print 'saveImageCache(%s) in %s' % (url, kf_account)
                kf['kf_headimgurl_cache'] = saveImageCache(url)
        kfsdict[kf_account] = kf            
            
    cache.set('content', kfsdict)
    cache.save()
    
def saveImageCache(url):
    from StringIO import StringIO
    from leancloud import File
    img = Object.extend('ImageCache')()
    ret = urllib2.urlopen(url)
    io = StringIO(ret.read())
    fname = url.split('?')[0]
    imgfile = File(fname, io, ret.headers.get('content-type'))
    img.set('url', url).set('imgfile', imgfile).save()
    return img.get('imgfile').url
 
    
def getkfsdict(isrefresh=False):
    kfs = Query(Object.extend('Cache_dict')).get(WECHATKFS_ID).get('content')
    if isrefresh:
        refreshkfs()
        kfs = Query(Object.extend('Cache_dict')).get(WECHATKFS_ID).get('content')
    return kfs
    
def getkfsession(openid):
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()     
    url = 'https://api.weixin.qq.com/customservice/kfsession/getsession?access_token=%s&openid=%s'
    return json.load(urllib2.urlopen(url % (ACTOKEN, openid)))
    
def getkfsessionlist(kfaccount):
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()     
    url = 'https://api.weixin.qq.com/customservice/kfsession/getsessionlist?access_token=%s&kf_account=%s'
    return json.load(urllib2.urlopen(url % (ACTOKEN, kfaccount)))
    
def getkfwaitcase():
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()     
    url = 'https://api.weixin.qq.com/customservice/kfsession/getwaitcase?access_token=%s'
    return json.load(urllib2.urlopen(url % ACTOKEN))
    
def getkfrecord(day=0):
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()     
    url = ' https://api.weixin.qq.com/customservice/msgrecord/getrecord?access_token=%s'
    now = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
    now = now.date() + datetime.timedelta(days=(1-day))
    now = time.mktime(now.timetuple())-1
    # now = int(time.time())
    i = 1
    data = {
        'endtime': now,
        'pageindex': i,
        'pagesize': 50,
        'starttime': now - 24*60*60+1
    }
    ret = urllib2.urlopen(url % ACTOKEN, json.dumps(data))
    ret = json.load(ret)
    result = {'recordlist': ret['recordlist']}
    while len(ret['recordlist']) == 50:
        i += 1
        data['pageindex'] = i
        ret = json.load(urllib2.urlopen(url % ACTOKEN, json.dumps(data)))
        result['recordlist'].extend(ret['recordlist'])
        
        
    return result
    
def createkf(openid, kf_account, text='ForceKfCreatTest'):
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()      
    url = 'https://api.weixin.qq.com/customservice/kfsession/create?access_token=%s'
    data = {
        'kf_account': kf_account,
        'openid': openid,
        'text': text
    }
    data = json.dumps(data)
    ret = urllib2.urlopen(url % ACTOKEN, data)
    ret = json.load(ret)
    return ret
    
def closekf(openid, kf_account, text='ForceKfCloseTest'):
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()
    url = 'https://api.weixin.qq.com/customservice/kfsession/close?access_token=%s'
    data = {
        'kf_account': kf_account,
        'openid': openid,
        'text': text    
    }
    data = json.dumps(data)
    ret = urllib2.urlopen(url % ACTOKEN, data)
    ret = json.load(ret)
    return ret
    
def sendableUserOpenids(limit=False, openid=None):
    now = int(time.time())
    limit_t = now - 48*60*60  # 48 hours
    query1 = Query(Object.extend('Log_Wechat_Message')).include('FromUserName', 'CreateTime')
    query2 = Query(Object.extend('Log_Wechat_Event')).include('FromUserName', 'CreateTime', 'Event')
    query2.not_equal_to('Event', 'TEMPLATESENDJOBFINISH')
    for q in [query1, query2]:
        q.greater_than('CreateTime', limit_t).descending('CreateTime').limit(1000)
    logs = query1.find()
    if openid:
        if Query(WechatUser).equal_to('openid', openid).equal_to('subscribe', 1).find():
            ret = query1.equal_to('FromUserName', openid).limit(1).find()        
            ret.extend(query2.equal_to('FromUserName', openid).limit(1).find())
            return max(t.get('CreateTime') for t in ret) if ret else False
        else:
            return
    if not limit:
        logs.extend(query2.find())
    else:
        from copy import deepcopy
        query3 = deepcopy(query2)
        query2.equal_to('EventKey', 'contactkf')
        query3.startswith('Event', 'kf_')
        logs.extend(Query.or_(query2, query3).find())
    logs.sort(key=lambda x:x.get('CreateTime'), reverse=True)
    openids = []
    subscribe = set()
    unsubscribe = set()
    info = {}
    for l in logs:
        openid = l.get('FromUserName')
        if openid not in info:
            info[openid] = [l.get('CreateTime'), False]
        if (
            l.get('MsgType')!='event' or 
            l.get('EventKey') == 'contactkf' or 
            (l.get('Event') is not None and 'kf_' in l.get('Event'))
            ):
            if not info[openid][1]:
                info[openid][1] = l.get('CreateTime')
        if l.get('Event') == 'subscribe':
            if openid not in unsubscribe:
                subscribe.add(openid)
        if l.get('Event') == 'unsubscribe':
            if openid not in subscribe:
                unsubscribe.add(openid)
        if openid not in openids:
            openids.append(openid)
        
    for t in unsubscribe:
        openids.remove(t)
    return {'openids': openids, 'info': info}
 
# ret = getkflist(True)
# print ret  
    
#---------------kf End -----------------#  
 
#---------------JSSDK ------------------#
def getjstoken_api():
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()
    url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi'
    ret = json.load(urllib2.urlopen(url % ACTOKEN))
  
    return ret.get('ticket', '')
    
def getjstoken():
    jstoken = Query(Object.extend('Cache')).get(JS_TICKET_ID)
    now = time.time()
    if jstoken.get('updatetime') + TOKENEXR < now:
        ticket = getjstoken_api()
        jstoken.set('content', ticket)
        jstoken.set('updatetime', now)
        jstoken.save()
    else:
        # print 'No need refresh!'
        ticket = jstoken.get('content')
    return ticket
    
def getjssign(cure_url):
    import random, string
    from hashlib import sha1
    noncestr = ''.join(random.choice(string.ascii_letters + string.digits) 
        for _ in range(15))
    timestamp = int(time.time())
    jsapi_ticket = getjstoken()
    vars = {
        'noncestr': noncestr,
        'jsapi_ticket': jsapi_ticket,
        'timestamp': str(int(timestamp)),
        'url': cure_url,
    }
    data = vars.items()
    data.sort(key=lambda x: x[0])
    data = '&'.join(['='.join(t) for t in data])
    # print data
    sign =  sha1(data).hexdigest()
    return {'signature': sign, 'timestamp': timestamp, 'nonceStr': noncestr, 'appId': APPID}

#---------------JSSDK End ------------------#
#-----------------About Auth-----------------#    
def getauthurl(re_url, info=False):
    scope='snsapi_base' if not info else 'snsapi_userinfo'
    url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=%s&redirect_uri=%s&response_type=code&scope=%s#wechat_redirect'
    re_url = urllib.quote(re_url,"")
    return url % (APPID, re_url, scope)
    
def getauth(code, info=False, save=False):
    url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code'
    for i in xrange(3):
        ret = json.load(urllib2.urlopen(url % (APPID, SECRET, code)))
        if ret.get('openid'):
            break
        print '(%s)GetAuthOpenidFaild:%s' % (i, ret)
    if info:
        access_token = ret.get('access_token')
        openid = ret.get('openid')
        url1 = 'https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN'
        ret = json.load(urllib2.urlopen(url1 % (access_token, openid)))
        if save and ret.get('openid'):
            wechatuser = WechatUser()
            ret.pop('privilege')
            for k in ret:
                wechatuser.set(k, ret[k])
            setNickname_emoji(wechatuser)
            wechatuser.save()
            ret['wechatuserid'] = wechatuser.id
        return ret 
    return ret.get('openid')
#---------------Auth End-----------------------#    
#---------------Image Manager------------------#    
def getimagedata(meidaid):
    ACTOKEN = getaccesstoken()
    url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s'
    ret = urllib2.urlopen(url % (ACTOKEN, meidaid))
    return ret

def uploadimage(imgurl):
    fp = urllib2.urlopen(imgurl)
    guessext = {
        'image/jpg': '.jpg', 'image/jpeg': '.jpg',
        'image/png': 'png',
    }
    fn = os.path.split(imgurl)[-1] + guessext.get(fp.headers.get('content-type'))
    files = {'file': (fn, fp)}
    import requests
    ACTOKEN = getaccesstoken()
    url = 'https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=image' % ACTOKEN
    ret = requests.post(url, files=files)
    
    return ret.json()

def sendimagefromurl(openid, url):
    ret = uploadimage(url)
    media_id = ret.get('media_id')
    if media_id:
        sendmessage(openid, media_id, 'image')
    else:
        print ret
    
#---------------End Image Manager------------#    
#-----------------XML REPLY ----------------#
TEXTXML = '''<xml>
<ToUserName><![CDATA[%(touser)s]]></ToUserName>
<FromUserName><![CDATA[%(fromuser)s]]></FromUserName>
<CreateTime>%(createtime)s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%(content)s]]></Content>
</xml>'''

KFXML = '''<xml>
    <ToUserName><![CDATA[%(touser)s]]></ToUserName>
    <FromUserName><![CDATA[%(fromuser)s]]></FromUserName>
    <CreateTime>%(createtime)s</CreateTime>
    <MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>'''

NEWSXML = '''<xml>
<ToUserName><![CDATA[%(touser)s]]></ToUserName>
<FromUserName><![CDATA[%(fromuser)s]]></FromUserName>
<CreateTime>%(createtime)s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%(count)s</ArticleCount>
<Articles>
%(articles)s</Articles>
</xml>'''
ARTICLEXML = '''<item>
<Title><![CDATA[%(title)s]]></Title> 
<Description><![CDATA[%(description)s]]></Description>
<PicUrl><![CDATA[%(picurl)s]]></PicUrl>
<Url><![CDATA[%(url)s]]></Url>
</item>
'''

def rev_xml_to_send_var(xml):
    rev_data = {}
    var = {}
    for t in xml:
        rev_data[t.tag] = t.text
    var['touser'] = rev_data['FromUserName']
    var['fromuser'] = rev_data['ToUserName']
    var['createtime'] = rev_data['CreateTime']
    
    return var
    
def replyTextMessage(content, xml):
    send_var = rev_xml_to_send_var(xml)
    send_var['content'] = content
    return TEXTXML % send_var
    
def replyNews(xml, items=None):
    var = rev_xml_to_send_var(xml)
    if not items:
        items = Query(Object.extend('Cache_list')).get(WECHATNEWITEMS_ID).get('content')
    articles = ''
    for item in items:
        articles += ARTICLEXML % item
    var.update({'count': len(items), 'articles': articles})
    return NEWSXML % var
    
#-------------XML End --------------#
#-------------Wechat Group----------#
def creategroup(gname):
    url = 'https://api.weixin.qq.com/cgi-bin/groups/create?access_token=%s'
    ACTOKEN = getaccesstoken()
    data = {'group': {'name': gname}}
    ret = json.load(urllib2.urlopen(url % ACTOKEN, json.dumps(data)))
    return ret
    
def getgroups():
    url = 'https://api.weixin.qq.com/cgi-bin/groups/get?access_token=%s' % getaccesstoken()
    ret = json.load(urllib2.urlopen(url))
    return ret
    
def getgroupid(openid):
    url = 'https://api.weixin.qq.com/cgi-bin/groups/getid?access_token=%s' % getaccesstoken()
    data = {'openid': openid}
    ret = json.load(urllib2.urlopen(url, json.dumps(data)))
    return ret
    
def updategroup(gid, gname):
    url = 'https://api.weixin.qq.com/cgi-bin/groups/update?access_token=%s' % getaccesstoken()
    data = {'group': {'id': gid, 'name': gname}}
    ret = json.load(urllib2.urlopen(url, json.dumps(data)))
    return ret
    
def movetogroup(openid, gid):
    if isinstance(openid, list):
        url = 'https://api.weixin.qq.com/cgi-bin/groups/members/batchupdate?access_token=%s' % getaccesstoken()
        data = {'openid_list': openid, 'to_groupid': gid}
    else:
        url = 'https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=%s' % getaccesstoken()
        data = {'openid': openid, 'to_groupid': gid}
    ret = json.load(urllib2.urlopen(url, json.dumps(data)))
    return ret 

def deletegroup(gid):
    url = 'https://api.weixin.qq.com/cgi-bin/groups/delete?access_token=%s' % getaccesstoken()
    data = {'group': {'id':gid}}
    ret = json.load(urllib2.urlopen(url, json.dumps(data)))
    return ret 
    
#-----------End Wechat Group----------#    


#----------- Media ----------#    
def get_medias(type='image', offset=0, count=20):
    try:        
        ACTOKEN = getaccesstoken()
    except RuntimeError:
        leancloud.init(LEANID, LEANKEY)
        ACTOKEN = getaccesstoken()    
    url = 'https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=%s'
    data = {
        'type': type,
        'offset': offset,
        'count': count
    }
    ret = json.load(urllib2.urlopen(url % ACTOKEN, json.dumps(data)))
    return ret
    
def get_medias_all(type='image'):
    items = []
    ret = get_medias(type)
    item_count = ret['item_count']
    total_count = ret['total_count']
    items.extend(ret['item'])
    if total_count > 20:
        i = 0
        while item_count == 20:
            i += 1
            print i
            ret = get_medias(type, offset=i*20)
            item_count = ret['item_count']
            items.extend(ret['item'])
    
    return items

def masspreview(content, mtype='text', openid=None, wxname=None):
    if not openid and not wxname:
        return 'NoUserGiven'
    ACTOKEN = getaccesstoken()
    url = 'https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token=%s' % ACTOKEN
    data = {'msgtype': mtype}
    if wxname:
        data['towxname'] = wxname
    else:
        data['touser'] = openid
    if mtype == 'text':
        import sys
        reload(sys)
        sys.setdefaultencoding('utf8')
        data['text'] = {'content': content}
    elif mtype in ['mpnews', 'voice', 'image', 'mpvideo']:
        data[mtype] = {'media_id': content} 

    ret = json.load(urllib2.urlopen(url, json.dumps(data)))
    return ret
    
def get_media(media_id):
    ACTOKEN = getaccesstoken()
    url = 'https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=%s' % ACTOKEN
    data = {'media_id': media_id}
    ret = json.load(urllib2.urlopen(url, json.dumps(data)))
    return ret
    

#-----------End Media ----------#    
#----------- Template ----------#    
def send_template(openid, t_id, url, t_data):
    for k in t_data:
        #t_data[k] = {'value': t_data[k], 'color': '#173177'}
        if isinstance(t_data[k], dict):
            continue
        t_data[k] = {'value': t_data[k], 'color': '#000000'}
    data = {
        "touser": openid,
        "template_id": t_id,
        "url": url,
        "data": t_data
    }
    ACTOKEN = getaccesstoken()
    api_url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=%s' % ACTOKEN
    ret = json.load(urllib2.urlopen(api_url, json.dumps(data)))
    return ret

def send_shop_order(openid, oid, order=None):
    if not order:
        order = get_order_detail(oid)['order']
    addr = u'{}{}{}{}'.format(
        order['receiver_province'],
        order['receiver_city'],
        order['receiver_zone'],
        order['receiver_address']
    )
    mobile = order['receiver_phone']
    des = u'({}件){}{}'.format(
        order['product_count'],
        order['product_name'],
        '(%s)' % order['product_sku'] if order['product_sku'] else ''
    )
    member = order['buyer_nick']
    data = {
        "keyword1": oid,
        "keyword2": {'value':des,'color':'#173177'},
        "keyword3": member,
        "keyword4": mobile, 
        "keyword5": addr
    }
    data['first'] = u"微信小店收到一个新订单"
    data['remark'] = u'收件人:{}\n邮编:{}\n消费价格:{}\n'.format(
        order['receiver_name'],
        order['receiver_zip'],
        '%.2f' % (order['order_total_price']/100.0)
    )
    #data['remark'] = u'此处为备注'
    t_id = 'pILeqywI3Iv8nl-3U0i3IKwTYtiC92Gnyk4KtkvvwFk'
    url = 'http://m.top-racer.com/shoporder?oid=%s' % oid
    ret = send_template(openid, t_id, url, data)
    return ret

def send_agm_order(openid, order=None):
    if not order:
        return
    des = u'({}件){}'.format(
        order['total_count'],
        order['product_name'],
    )
    data = {
        "keyword1": order['oid'],
        "keyword2": {'value':des,'color':'#173177'},
        "keyword3": order['member'],
        "keyword4": order['mobile'], 
        "keyword5": order['addr']
    }
    data['first'] = u"AGM订货系统收到一个新订单"
    data['remark'] = u'收件人:{}\n货运公司:{}\n订单总额:{}元\n'.format(
        order['receiver_name'],
        order['ship_company'],
        '%.2f' % (order['order_total_price'])
    )
    #data['remark'] = u'此处为备注'
    t_id = 'pILeqywI3Iv8nl-3U0i3IKwTYtiC92Gnyk4KtkvvwFk'
    url = 'http://www.top-racer.com/order_admin/orderDetail.php?oid=%s' % order['oid']
    ret = send_template(openid, t_id, url, data)
    return ret
    
def send_order_confirm(openid, oid, order=None):
    if not order:
        order = get_order_detail(oid)['order'] 
    addr = u'{}{}{}{}'.format(
        order['receiver_province'],
        order['receiver_city'],
        order['receiver_zone'],
        order['receiver_address']
    )
    member = order['buyer_nick']
    data = {
        "keyword1": {'value':addr,'color':'#173177'},
        "keyword2": {'value':order['receiver_name'],'color':'#173177'},
        "keyword3": {'value':order['receiver_phone'],'color':'#173177'},
    }
    data['first'] = u'您已成功订购音速风暴产品\n请认真核对以下收货信息'
    data['remark'] = u'如果发现以上收货信息有误,请尽快与我司客服人员联系\n如以上信息无误,我们将尽快安排发货\n感谢您对音速风暴产品的支持'
    t_id = 'g-2Jwu9J0mp6aDZL5Yv0KBBYhB7u8UOgfuAUB76zXHs'
    url = 'http://m.top-racer.com/shoporder?oid=%s' % oid
    ret = send_template(openid, t_id, url, data)
    return ret
    
def get_order_detail(oid):
    ACTOKEN = getaccesstoken()
    api_url = 'https://api.weixin.qq.com/merchant/order/getbyid?access_token=%s' % ACTOKEN
    data = {'order_id': oid}
    ret = json.load(urllib2.urlopen(api_url, json.dumps(data)))
    return ret

def get_orders(status=None):
    ACTOKEN = getaccesstoken()
    api_url = 'https://api.weixin.qq.com/merchant/order/getbyfilter?access_token=%s' % ACTOKEN
    data = {'status': status}
    ret = json.load(urllib2.urlopen(api_url, json.dumps(data)))
    return ret
    
def close_order(oid):
    ACTOKEN = getaccesstoken()
    api_url = 'https://api.weixin.qq.com/merchant/order/close?access_token=%s' % ACTOKEN
    data = {'order_id': oid}
    ret = json.load(urllib2.urlopen(api_url, json.dumps(data)))
    return ret    

def send_kf_message(openid, nickname, text, url):
    t_id = 'ACazU5CLDXx_DV_fJ06nMGSaGRwybuJEluATDZnJPds'
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    data = {
        "keyword1": {'value':nickname,'color':'#173177'},
        "keyword2": u"微信用户",
        "keyword3": {'value':now,'color':'#173177'},
        "keyword4": u"公众号留言",
        "keyword5": "内容如下",
        "remark": {'value':text,'color':'#173177'},
        "first": "收到一条来自音速风暴公众号的客户咨询"
    }
    #url = 'http://m.top-racer.com/kfchat?uid=%s'
    #url = 'http://m.top-racer.com/kfchat'
    ret = send_template(openid, t_id, url, data)
    
def send_repair_message(openid, place, title, text):
    t_id = 'bFiTqukBtjM76Bue3pYrWRfvIhdwssq1MCHQqtjdnJI'
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    data = {
        "keyword1": {'value':place,'color':'#173177'},
        "keyword2": u"无",
        "keyword3": {'value':title,'color':'#173177'},
        "keyword4": u"无",
        "keyword5": {'value':now,'color':'#173177'},
        "remark": {'value':text,'color':'#173177'},
        "first": "收到一条来自英宝玩具公司的报修信息"
    }
    url = 'http://m.top-racer.com/agmstaff/repair'
    #url = 'http://m.top-racer.com/kfchat'
    ret = send_template(openid, t_id, url, data)    
    
def send_report_message(openid, r_mode, name, depart, phone, r_type, des):
    t_id = 'D1rTyY5Ju0FgJOglG3DChyNc28x87V1WHTm1WRtBwz4'
    now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    first = u"收到一条来自员工的" + r_mode[0]
    first += "\n" + r_mode[0] + u"人：" + name
    first += u"\n所在部门：" + depart
    first += u"\n联系电话：" + phone
    first += "\n" + r_mode[0] + u"对象：" + r_type
    first += "\n" + r_mode[0] + u"内容：" + des
    data = {
        "keyword1": {'value':"未处理",'color':'#173177'},
        "keyword2": {'value':now,'color':'#173177'},
        "remark": {'value':"点击查看列表",'color':'#173177'},
        "first": first
    }
    url = 'http://m.top-racer.com/agmstaff/' + r_mode[1]
    #url = 'http://m.top-racer.com/kfchat'
    ret = send_template(openid, t_id, url, data)       
    
#-----------End Template ----------#    

if __name__ == '__main__':
    leancloud.init(LEANID, master_key='Q1SCs9WsR1XxBUm8ExkthOVb')
    # ret = get_media('4dZlH3ctxkcBJXhpszR6Uv6RHaDfJCOR6sSUM1kitkM')
    # previewsopenids = ['ohCrcvpGGtIBJTNo5LUpR2dfb-Us', 'ohCrcvngXDgu-CulbG2S2IDXYbt4', 'ohCrcvlQMzCovAxALwzdNOs8yNf8', 'ohCrcvq5TTqoF1eP4p2oLn6rte2k']
    # previewsopenids = ['ohCrcvpGGtIBJTNo5LUpR2dfb-Us', 'ohCrcvlQMzCovAxALwzdNOs8yNf8']
    # for openid in previewsopenids:
        # ret = masspreview('Zb8jf9JzMIS_xQd9te_qsqNjxoAFZ7KGP72bsZ47t4g', 'mpnews', openid)
        # print ret
    # ret = masspreview('4dZlH3ctxkcBJXhpszR6Ujtwl2aRscwqZNdSRMbl1H8', 'mpnews', 'ohCrcvq5TTqoF1eP4p2oLn6rte2k')
    # ret = get_medias('news')
    # for t in ret['item']:
        # print t['media_id'], t['content']['news_item'][0]['title']
    # ret = getqrcode(99998, 60*60*24*8)
    # ret = closekf('ohCrcvlQMzCovAxALwzdNOs8yNf8', 'test2@ysfblgsc')
    # print ret
    # ret = get_save_userinfo_api('ohCrcvq5TTqoF1eP4p2oLn6rte2k')
    # ret = getkflist(True)
    # print ret
    # sendqrcode('ohCrcvlQMzCovAxALwzdNOs8yNf8', 4836)
    # ret = getjssign('asdfasdjklsadf')
    # content = Query(Object.extend('Cache_list')).get(WECHATNEWITEMS_ID).get('content')
    # content = content[:1]
    # content[0]['url'] = ''
    # ret = sendmessage('ohCrcvlQMzCovAxALwzdNOs8yNf8', 'Lls0-6n6cDpyrPuhBUXQI_X5epdw_qs0TLRqv9PrkgU', 'image')
    # ret = sendmessage('ohCrcvq5TTqoF1eP4p2oLn6rte2k', 'P8l0rLWz6XlciyA372G9t_xIVbpc53TV924gMdSbbz0', 'image')
    # getaccesstoken()
    # pass
    # ACTOKEN = getaccesstoken()
    # ret = getqrcode('imfunimfun', expire_seconds=None)
    # openids = get_openids_api()
    # for openid in openids:
        # print get_save_userinfo_api(openid).dump()
    #ret = send_shop_order('ohCrcvlQMzCovAxALwzdNOs8yNf8', '123456', u"测试商品", "imfun", 12345678911, "测试地址")
    # ret = get_order_detail('13752914108930839369')
    # ret = send_shop_order('ohCrcvlQMzCovAxALwzdNOs8yNf8', '13752914108930791231')
    # ret = send_order_confirm('ohCrcvlQMzCovAxALwzdNOs8yNf8', '13752914108930798075')
    # ret = send_kf_message('ohCrcvlQMzCovAxALwzdNOs8yNf8', 'imfun', '你好啊,我有问题想请问一下', 'http://m.top-racer.com/kfchat')
    #order = {}
    #order['addr'] = u'测试收货地址'
    #order['mobile'] = u'测试电话'
    #order['total_count'] = 2
    #order['product_name'] = u'测试货号'
    #order['member'] = u'测试用户名'
    #order['oid'] = u'测试单号'
    #order['receiver_name'] = u'测试收件人'
    #order['ship_company'] = u'测试货运公司'
    #order['order_total_price'] = 100
    #send_agm_order('ohCrcvlQMzCovAxALwzdNOs8yNf8', order)
